package cn.db101.fairy.service

import cn.db101.fairy.api.AccessTokenRequest
import cn.db101.fairy.api.QrcodeRequest
import cn.db101.fairy.api.WxApi
import cn.db101.fairy.config.FairyConfigProperties
import cn.db101.fairy.model.PullQrcodeRequest
import cn.hutool.core.codec.Base64
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service

/**
 * @author zooy
 * @since 2025/3/26-9:45
 */
@Service
class WxService {

    @Autowired
    lateinit var wxApi: WxApi

    @Autowired
    lateinit var fairyConfigProperties: FairyConfigProperties

    var accessToken: String? = null

    @Scheduled(fixedDelay = 1000 * 60 * 60 * 2)
    fun getWxAccessToken() {

        if (accessToken == null) {
            val accessTokenReponse = wxApi.getWxAccessToken(AccessTokenRequest().also {
                it.appId = fairyConfigProperties.appId
                it.secret = fairyConfigProperties.appSecret
            })
            accessToken = accessTokenReponse.access_token
            println("accessToken: ${accessTokenReponse.access_token}")
        }
    }

    fun pullQrcode(pullQrcodeRequest: PullQrcodeRequest): String {

        val qrcodeBytes = wxApi.getUnlimitedQrcode(accessToken!!, QrcodeRequest().also {
            it.scene = pullQrcodeRequest.scene
        })

        val imageBase64 = Base64.encode(qrcodeBytes)
        println("pullQrcode: ${imageBase64}")

        return "data:image/jpg;base64,$imageBase64"
    }

}
